package org.kjtc.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.kjtc.annotations.Event;
import org.kjtc.entity.ChargingStation;
import org.kjtc.entity.ChargingStationStatus;
import org.kjtc.entity.DeviceObject;
import org.kjtc.entity.Page;
import org.kjtc.entity.SingleStation;
import org.kjtc.service.ActionHistoryService;
import org.kjtc.service.ChargingRecordService;
import org.kjtc.service.ChargingStationService;
import org.kjtc.util.Const;
import org.kjtc.util.FileDownload;
import org.kjtc.util.FileUpload;
import org.kjtc.util.Tools;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class ChargingStationController extends BaseController {

	@Resource(name = "actionHistoryService")
	private ActionHistoryService actionHistoryService;

	@Resource(name = "chargingStationService")
	private ChargingStationService chargingStationService;

	@Resource(name = "chargingRecordService")
	private ChargingRecordService chargingRecordService;

	@Resource(name = "deviceObject")
    private DeviceObject deviceObject;

	@Event("充电站掉线")
	public void offlineAlarm(String chargingstationID) {
		System.out.println(chargingstationID);
	}

	@RequestMapping(value = "/searchChargingStation")
	@ResponseBody
	/*
	 * 充电站查询
	 */
	public Map<String, Object> searchChargingstation(ChargingStation chargingstation, String page, String rows) {

		Map<String, Object> map = new HashMap<String, Object>();
		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "充电站信息查询开始");
		// 分页
		Page pageQuery = getPage();
		pageQuery.setCurrentPage(Integer.parseInt(page));
		pageQuery.setCurrentResult((Integer.parseInt(page) - 1) * (Integer.parseInt(rows)));
		pageQuery.setShowCount(Integer.parseInt(rows));

		List<ChargingStation> chargingStationList = null;
		try {
			if (chargingstation.getBranchCompanyID() == null || chargingstation.getBranchCompanyID().isEmpty()) {
				chargingstation.setBranchCompanyID(this.getBranchCompanyID());
			}
			chargingStationList = chargingStationService.getChargingStationPage(chargingstation, pageQuery);
			File folder = null;
			List<String> fileNameList = null;
			for (ChargingStation chargingStation : chargingStationList) {
				folder = new File(Const.SYSTEMCONFIG_PATH_BUS + chargingStation.getChargingStationID() + File.separator);
				fileNameList = new ArrayList<String>();
				if (folder.exists()) {
					File[] files = folder.listFiles();
					for (File imageFile : files) {
						fileNameList.add(imageFile.getName());
					}
				}
				chargingStation.setChargingStationImageName(fileNameList);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "充电站信息查询异常" + e.getMessage());
			return map;
		}

		map.put("totalCnt", pageQuery.getTotalResult());
		map.put("totalPage", pageQuery.getTotalPage());
		map.put("chargingstationList", chargingStationList);
		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "充电站信息查询结束");
		actionHistoryService.saveActionHistory(this.getUesr().getUserID(), "充电站信息查询");
		chargingstation = null;

		return map;
	}
	/*
	 * 充电站添加
	 */
	@RequestMapping(value = "/saveChargingStation")
	@ResponseBody
	public Map<String, Object> saveChargingstation(ChargingStation chargingstation) {

		Map<String, Object> map = new HashMap<String, Object>();
		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "充电站信息添加开始");
		chargingstation.setCreateUser(this.getUesr().getUserID());
		chargingstation.setUpdateUser(this.getUesr().getUserID());
		int count = 0;
		try {
			count = chargingStationService.insertChargingStation(chargingstation);
			if (count > 0) {
				map.put("result", "Success");
				map.put("chargingStationID", chargingstation.getChargingStationID());
				this.setSessionAttribute(Const.SESSION_CHARGINGSTATIONNAME, null);
			} else {
				map.put("result", "NotFound");
			}
		} catch (DuplicateKeyException ex) {
			String[] error = ex.getCause().getMessage().split("'");
			if ("ChargingStationNO".equals(error[3].trim())) {
				map.put("result", "ChargingStationNOExist");
			} else if ("ChargingStationName".equals(error[3].trim())){
				map.put("result", "ChargingStationNameExist");
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put("result", "Error");
		    logger.error(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "充电站信息添加异常" + e.getMessage());
		}
		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "充电站信息添加结束");
		actionHistoryService.saveActionHistory(this.getUesr().getUserID(), "充电站信息添加");
		chargingstation = null;
		return map;
	}

	/*
	 * 充电站修改
	 */
	@RequestMapping(value = "/updateChargingStation")
	@ResponseBody
	public Map<String, Object> updateChargingStation(ChargingStation chargingstation) {

		Map<String, Object> map = new HashMap<String, Object>();
		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "充电站信息修改开始");
		chargingstation.setUpdateUser(this.getUesr().getUserID());
//		chargingstation.setOpenDTTM(Tools.str2DateTime(chargingstation.getOpenDate()));
//		chargingstation.setCloseDTTM(Tools.str2DateTime(chargingstation.getCloseDate()));
		int count = 0;
		try {
			count = chargingStationService.updateChargingStation(chargingstation);
			if (count > 0) {
				map.put("result", "Success");
				map.put("chargingStationID", chargingstation.getChargingStationID());
				this.setSessionAttribute(Const.SESSION_CHARGINGSTATIONNAME, null);
			} else {
				map.put("result", "NotFound");
			}
		} catch (DuplicateKeyException ex) {
			String[] error = ex.getCause().getMessage().split("'");
			if ("ChargingStationNO".equals(error[3].trim())) {
				map.put("result", "ChargingStationNOExist");
			} else if ("ChargingStationName".equals(error[3].trim())){
				map.put("result", "ChargingStationNameExist");
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put("result", "Error");
			logger.error(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "充电站信息修改异常" + e.getMessage());
		}
		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "充电站信息修改结束");
		actionHistoryService.saveActionHistory(this.getUesr().getUserID(), "充电站信息修改");
		chargingstation = null;
		return map;
	}

	/*
	 * 充电站删除
	 */
	@RequestMapping(value = "/deleteChargingStation")
	@ResponseBody
	public Object deleteChargingStation(String chargingStationID) {

		Map<String, Object> map = new HashMap<String, Object>();
		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "充电站信息删除开始");
		String [] chargingStationIDList = chargingStationID.split(",");
		ChargingStation chargingstation = new ChargingStation();
		chargingstation.setChargingStationIDList(chargingStationIDList);
		int count = 0;
		try {
			count = chargingStationService.deleteChargingStation(chargingstation);
			if (count > 0) {
				map.put("result", "Success");
				int length = chargingStationIDList.length;
				File folder = null;
				for (int i = 0; i < length; i++) {
					folder = new File(Const.SYSTEMCONFIG_PATH_BUS + chargingStationIDList[i] + File.separator);
					if (folder.exists()) {
						File[] files = folder.listFiles();
						for (File imageFile : files) {
							imageFile.delete();
						}
						folder.delete();
					}
					folder = null;
				}
				this.setSessionAttribute(Const.SESSION_CHARGINGSTATIONNAME, null);
			} else {
				map.put("result", "NotFound");
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put("result", "Error");
			logger.error(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "充电站信息删除异常:" + e.getMessage());
		}
		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "充电站信息删除结束");
		actionHistoryService.saveActionHistory(this.getUesr().getUserID(), "充电站信息删除");
		chargingstation = null;
		return map;
	}

	@ResponseBody
	@RequestMapping(value = "/saveChargingStationImage")
	public Object saveChargingStationImage(@RequestParam(value="chargingStationImage", required=false) MultipartFile[] files,
			@RequestParam(value="subfolder", required=false) String subfolder) {

		Map<String, Object> map = new HashMap<String, Object>();
		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "上传充电站图片开始");
		String filePath = Const.SYSTEMCONFIG_PATH_BUS + subfolder + File.separator;
		int length = files.length;
		for (int i = 0; i < length; i++ ) {
			if (files[i] != null && !files[i].isEmpty()) {
				String fileName = null;
				try {
					fileName = FileUpload.upload(files[i], filePath, files[i].getOriginalFilename(), null);
					map.put("result", "Success");
					logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "上传充电站图片【" + files[i].getOriginalFilename() + "】已成功上传到" + filePath + fileName);
					actionHistoryService.saveActionHistory(this.getUesr().getUserID(), "上传充电站图片【" + files[i].getOriginalFilename() + "】已成功上传到" + filePath + fileName);
				} catch (IOException e) {
					map.put("error", "上传充电站图片【" + files[i].getOriginalFilename() + "】异常:" + e.getMessage());
					logger.error(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "上传充电站图片【" + files[i].getOriginalFilename() + "】异常:" + e.getMessage());
				}
			} else {
				map.put("error", "上传充电站图片失败，请重新上传！");
			}
		}
		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "上传充电站图片结束");
		return map;
	}

	@ResponseBody
	@RequestMapping(value = "/deleteChargingStationImage")
	public Object deleteChargingStationImage(@RequestParam(value="fileName", required=false) String fileName,
			@RequestParam(value="subfolder", required=false) String subfolder) {

		Map<String, Object> map = new HashMap<String, Object>();
		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "删除充电站图片开始");
		File file = new File(Const.SYSTEMCONFIG_PATH_BUS + subfolder + File.separator + fileName);
		if (file.exists()) {
			file.delete();
			logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "删除充电站图片：" + fileName);
			actionHistoryService.saveActionHistory(this.getUesr().getUserID(), "删除充电站图片：" + fileName);
			map.put("result", "Success");
		} else {
			map.put("error", "删除充电站图片不存在！");
		}
		file = null;
		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "上传充电站图片结束");
		return map;
	}

	@RequestMapping(value = "/getChargingStationImage")
	public void getChargingStationImage(@RequestParam(value="fileName", required=false) String fileName,
			@RequestParam(value="subfolder", required=false) String subfolder, HttpServletResponse response) {

//		String filePath = Const.SYSTEMCONFIG_PATH_BUS + subfolder + File.separator + fileName;
		String filePath = Const.SYSTEMCONFIG_PATH_BUSSM + subfolder + File.separator + fileName;
		File file = new File(filePath);
		if (file.exists()) {
			try {
				FileDownload.fileDownload(response, filePath, fileName);
				logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "获取充电站图片：" + fileName);
				actionHistoryService.saveActionHistory(this.getUesr().getUserID(), "获取充电站图片：" + fileName);
			} catch (Exception e) {
				e.printStackTrace();
				logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "获取充电站图片异常：" + e.getMessage());
			}
		} else {
			logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "获取充电站图片不存在！");
		}
		file = null;
	}

	@ResponseBody
	@RequestMapping(value = "/saveWebcamImage")
	public Object saveWebcamImage(@RequestParam(value="image", required=false) String image,
			@RequestParam(value="chargingStationID", required=false) String chargingStationID,
			@RequestParam(value="webcamID", required=false) String webcamID) {

		Map<String, Object> map = new HashMap<String, Object>();
		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "保存摄像头拍照图片开始");
		String filePath = Const.WEBCAM_PATH;
		if (chargingStationID == null || chargingStationID.isEmpty()) {
			map.put("result", "ChargingStationIDNull");
			logger.error(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "保存摄像头拍照图片失败：保存路径的充电站ID为空！");
		} else if (webcamID == null || webcamID.isEmpty()) {
			map.put("result", "WebcamIDNull");
			logger.error(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "保存摄像头拍照图片失败：保存路径的摄像头ID为空！");
		} else if (image == null || image.isEmpty()) {
			map.put("result", "ImageNull");
			logger.error(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "保存摄像头拍照图片失败：图片不存在！");
		} else {
			filePath = filePath + chargingStationID + File.separator + webcamID + File.separator;
			filePath = filePath + Tools.date2Str(new Date(), "yyyyMMddHHmmss") + Const.IMG_SUFFIX;
			try {
				image = image.replace("data:image/png;base64,", "").trim();
				Tools.saveBase64DataToImage(image, filePath);
				logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "保存摄像头拍照图片成功");
				actionHistoryService.saveActionHistory(this.getUesr().getUserID(), "保存摄像头拍照图片");
				map.put("result", "Success");
			} catch (Exception e) {
				e.printStackTrace();
				logger.error(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "保存摄像头拍照图片异常：" + e.getMessage());
				map.put("result", "error");
			}
		}
		logger.info("保存摄像头拍照图片结束");
		return map;
	}

	@RequestMapping(value = "getChargingStationMapStatus")
	@ResponseBody
    public Object getChargingStationMapStatus(String chargingStationID, SingleStation singleStation) {

		Map<String, Object> map = new HashMap<String, Object>();
		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "获取充电站地图状态开始");
		List<SingleStation> singleStationList = null;
		map.put("onlineStatus", "断开");
		map.put("onLineCount", 0);
		Map<String, Object> subStationMap = deviceObject.getSubStationMap();
		if (subStationMap != null && subStationMap.containsKey(chargingStationID)){
			ChargingStationStatus chargingStationStatus = (ChargingStationStatus)subStationMap.get(chargingStationID);
			Date requestDTTM = chargingStationStatus.getRequestDTTM();
			if (requestDTTM != null) {
				Date now = new Date();
				long second = (now.getTime() - requestDTTM.getTime()) / 1000;
				if (second < Const.SUBSTATION_OUTLINETIME) {
					map.put("onlineStatus", "在线");
					map.put("onLineCount", chargingStationStatus.getEquipmentChargingCount() + chargingStationStatus.getEquipmentChargedCount());
				}
			}
		}
		try {
			if (singleStation.getBranchCompanyID() == null || singleStation.getBranchCompanyID().isEmpty()) {
				singleStation.setBranchCompanyID(this.getBranchCompanyID());
			}
			singleStationList = chargingRecordService.getSingleStationMsg(singleStation);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "地图单个站查询异常" + e.getMessage());
			return map;
		}
		map.put("singleStationList", singleStationList);
		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "获取充电站地图状态结束");
		singleStation = null;
		return map;
	}
}